(function($, doc) {
	/*
	localforage.config({
		driver: localforage.WEBSQL, // INDEXEDDB/WEBSQL/LOCALSTORAGE
		name: 'myApp',
		version: 1.0,
		size: 4980736, // Size of database, in bytes. WebSQL-only for now.
		storeName: 'keyvaluepairs', // Should be alphanumeric, with underscores.
		description: 'some description'
	});*/
	$.init();
	var lauchFlag = localStorage.getItem('lauchFlag');
	if(!lauchFlag) {
		$.openWindow({
			url: 'guide.html',
			id: 'guide',
			show: {
				aniShow: 'pop-in'
			},
			waiting: {
				autoShow: false
			}
		});
	}
	$.plusReady(function() {
		//console.log(plus.os.language);
		var langset = localStorage.getItem('defaultLan');
		if(!langset) {
			if(plus.os.language != 'zh_CN') {
				localStorage.setItem('defaultLan', 'en');
			} else {
				localStorage.setItem('defaultLan', 'zh');
			}

		}

		plus.screen.lockOrientation("portrait-primary");
		var settings = app.getSettings();
		var state = app.getState();
		setTimeout(function() {
			//关闭 splash
			plus.navigator.closeSplashscreen();
			plus.nativeUI.closeWaiting();
		}, 100);
		/*
		var mainPage = plus.webview.getWebviewById("main.html");
		var main_loaded_flag = false;
		if(!mainPage) {
			mainPage = $.preload({
				"id": 'main.html',
				"url": 'main.html',
				createNew:true
			});
		} else {
			main_loaded_flag = true;
		}

		mainPage.addEventListener("loaded", function() {
			main_loaded_flag = true;
		});*/

		var toMain = function() {
			location.href = 'main.html';
			//plus.webview.open( 'main.html', 'main.html');
			/*
			var id = setInterval(function() {
				if(main_loaded_flag) {
					clearInterval(id);
					$.fire(mainPage, 'show', null);
					mainPage.show("pop-in");
				}
			}, 5);
			
			mui.openWindow({id : 'main.html', url : 'main.html',
                            show:{                               
                                aniShow:"slide-in-right",
                                duration:300,
                                autoShow:false
                                 },
                             waiting:{
                                title:"正在加载，请稍后..."
                             }});*/
		};
		//检查 "登录状态/锁屏状态" 结束
		var loginButton = doc.getElementById('login');
		var accountBox = doc.getElementById('account');
		var passwordBox = doc.getElementById('password');
		//var autoLoginButton = doc.getElementById("autoLogin");
		var regButton = doc.getElementById('reg');
		//var forgetButton = doc.getElementById('forgetPassword');
		//检查 "登录状态/锁屏状态" 开始
		/*
		if(settings && settings.autoLogin && state.token && settings.gestures) {
			$.openWindow({
				url: 'unlock.html',
				id: 'unlock',
				show: {
					aniShow: 'pop-in'
				},
				waiting: {
					autoShow: false
				}
			});
		} else if(settings.autoLogin && state.token) {
			toMain();
		}*/
		var users = app.getUsers();
		if(state.user_id) {
			toMain();
		}

		var lastUser = app.getOneUser();
		if(!lastUser) {
			//切换做好后要跳到手机登录
			location.href = 'shift_user.html';
			return;
		}
		//var out_phone = localStorage.getItem('_out_phone');
		//var phones = out_phone.substr(0, 3) + ' ' + out_phone.substr(3, 4) + ' ' + out_phone.substr(-4);
		//doc.getElementById('phone').innerText = phones;
		//var at = localStorage.getItem('_out_avatar');
		//doc.getElementById('avatar').src = at;
		var out_phone = lastUser.phone;
		var phones = out_phone.substr(0, 3) + ' ' + out_phone.substr(3, 4) + ' ' + out_phone.substr(-4);
		doc.getElementById('phone').innerText = phones;
		doc.getElementById('account').value = lastUser.phone;
		//var avatar = serverurl + 'upload/avatar/' + lastUser.user_id + '.jpg';
		//console.log(avatar);
		//doc.getElementById('avatar').src =  'static/images/1.jpg';
		//console.log(doc.getElementById('avatar').src);
		var log_type = document.getElementById('login_type').value;
		//localStorage.removeItem('_send_code');
		//点击找回密码
		document.getElementById("forgetPassword").addEventListener('tap', function() {
			mui.openWindow({
				url: 'find_pwd_list.html',
				id: 'find_pwd_list'
			});
		});
		passwordBox.addEventListener('input', function() {
			if(passwordBox.value != '') {
				loginButton.removeAttribute('disabled');
			} else {
				loginButton.setAttribute('disabled', 'disabled');
			}
		});
		document.getElementById('code').addEventListener('keyup', function() {
			if(document.getElementById('code').value != '') {
				document.getElementById('login').removeAttribute('disabled');
			} else {
				document.getElementById('login').setAttribute('disabled', 'disabled');
			}
		});

		mui('.mui-input-row').on('tap', '.mui-icon.mui-icon-clear', function() {
			document.getElementById('login').setAttribute('disabled', 'disabled');
		});

		mui('#pwd_div').on('tap', 'a', function() {
			document.getElementById('pwd_div').style.display = 'none';
			document.getElementById('phone_code_div').style.display = 'block';
			document.getElementById('login_type').value = 2;
		});

		mui('#phone_code_div').on('tap', 'a', function() {
			document.getElementById('pwd_div').style.display = 'block';
			document.getElementById('phone_code_div').style.display = 'none';
			document.getElementById('login_type').value = 1;
		});

		document.getElementById("getCode").addEventListener('tap', function() {
			//localStorage.removeItem('_send_code');
			var c1 = 60,
				phone = document.getElementById('account').value;
			if(phone == '' || !(/^1(3|4|5|7|8)\d{9}$/.test(phone))) {
				plus.nativeUI.toast("手机号码有误，请重填手机号");
			}
			var btnArray = ['确定', '取消'];
			mui.confirm('我们将发送验证码短信到下面的号码：\n' + phone, '确认手机号码', btnArray, function(e) {
				if(e.index == 0) {
					mui.get(apiurl + 'index/sms', {
						'phone': phone
					}, function(res) {
						if(res.status == 1) {
							plus.nativeUI.toast('发送短信成功');
							//发送短信成功
							//localStorage.setItem('_send_code', res.ck_code);
						} else {
							plus.nativeUI.toast(res.msg);
							document.getElementById('getCode').innerHTML = '获取验证码';
							document.getElementById('getCode').removeAttribute('disabled');
							c1 = 60;
							return;
						}
						var code1 = setInterval(function() {
							document.getElementById('getCode').innerHTML = c1 + '秒后重新获取';
							c1 = c1 - 1;
							if(c1 >= 0) {
								document.getElementById('getCode').setAttribute("disabled", "disabled");
							} else {
								document.getElementById('getCode').innerHTML = '获取验证码';
								document.getElementById('getCode').removeAttribute('disabled');
								c1 = 60;
								clearInterval(code1);
							}
						}, 1000);
					});
				}

			})

		});
		function ajaxlogin(loginInfo){
			console.log(JSON.stringify(loginInfo));
			$.ajax({
				url: loginurl,
				data: loginInfo,
				async: true,
				dataType: 'json',
				crossDomain: true, //强制使用5+跨域
				type: 'post',
				timeout: 10000,
				success: function(res) {
					console.log(JSON.stringify(res));
					// 请求成功
					if(res.status < 1) {
						mui.alert(res.msg);
					} else {
						//localStorage.removeItem('_send_code');
						app.createState(res.userinfo);
						app.setUsers(res.userinfo);
						console.log(res.userinfo.user_id);
						//toMain();

					}
				},
				error: function(xhr, type, errorThrown) {
					console.log(JSON.stringify(xhr));
					console.log(JSON.stringify(type));
					console.log(JSON.stringify(errorThrown));
					// 请求失败
				}
			});
		}
		loginButton.addEventListener('tap', function(event) {
			var log_type = document.getElementById('login_type').value;
			//toMain();
			var loginInfo = {
				//	account: accountBox.value,
				account: lastUser.phone,
				//password: passwordBox.value
				password: passwordBox.value,
				code: document.getElementById('code').value,
				login_type: log_type
			};
			/*
			if(!(/^1(3|4|5|7|8)\d{9}$/.test(loginInfo.account))) {
				plus.nativeUI.toast("手机号码有误，请重填");
				return;
			}*/
			//console.log(log_type);
			if(log_type < 2) {
				//loginInfo.password = passwordBox.value;
				if(loginInfo.password.length < 6) {
					plus.nativeUI.toast(lang('密码最短为 6 个字符'));
					return;
				}

				loginInfo.passwd = md5(loginInfo.password);
				if(loginInfo.passwd == lastUser.pwd) {
					app.createState(lastUser);
					toMain();
					return;
				}
			} else {
				if(document.getElementById('code').value == '') {
					plus.nativeUI.toast('请填写验证码');
					return;
				}

				//loginInfo.code = document.getElementById('code').value;
			}
			
			setTimeout(function(){
				ajaxlogin(loginInfo);
			},100);
			/*
			mui.post(loginurl, loginInfo, function(res) {
				console.log(JSON.stringify(res));
				
			});*/
			return;
		});
		/*$.enterfocus('#login-form input', function() {
			$.trigger(loginButton, 'tap');
		});
		
		autoLoginButton.classList[settings.autoLogin ? 'add' : 'remove']('mui-active');
		autoLoginButton.addEventListener('toggle', function(event) {
			setTimeout(function() {
				var isActive = event.detail.isActive;
				settings.autoLogin = isActive;
				app.setSettings(settings);
			}, 50);
		}, false); */
		regButton.addEventListener('tap', function(event) {
			var po = $('.mui-popover.mui-popover-action.mui-popover-bottom')[0];
			var cname = po.className;
			cname = cname.replace('mui-active', '');
			po.className = cname;
			po.style.display = 'none';
			$('.mui-backdrop.mui-active')[0].style.display = 'none';

			$.openWindow({
				url: 'reg.html',
				id: 'reg',
				preload: true,
				show: {
					aniShow: 'pop-in'
				},
				styles: {
					popGesture: 'hide'
				},
				waiting: {
					autoShow: false
				}
			});
		}, false);

		doc.getElementById('shift_user').addEventListener('tap', function(event) {
			var po = $('.mui-popover.mui-popover-action.mui-popover-bottom')[0];
			var cname = po.className;
			cname = cname.replace('mui-active', '');
			po.className = cname;
			po.style.display = 'none';
			$('.mui-backdrop.mui-active')[0].style.display = 'none';
			location.href = 'shift_user.html';
			/*
			$.openWindow({
				url: 'shift_user.html',
				id: 'shift_user',
				preload: true,
				show: {
					aniShow: 'pop-in'
				},
				styles: {
					popGesture: 'hide'
				},
				waiting: {
					autoShow: false
				}
			});*/
		}, false);

		var backButtonPress = 0;
		$.back = function(event) {
			backButtonPress++;
			if(backButtonPress > 1) {
				plus.runtime.quit();
			} else {
				plus.nativeUI.toast('再按一次退出应用');
			}
			setTimeout(function() {
				backButtonPress = 0;
			}, 1000);
			return false;
		};
	});
}(mui, document));